import * as React from "react";
import PropTypes from 'prop-types';
import {
    Labeled, useTranslate, DateTimeInput,
    Button,
    useRedirect,
    downloadCSV,
    useListContext,
    DateInput
} from 'react-admin';
import moment from 'moment'

import IconEvent from '@material-ui/icons/Event';
import GetAppIcon from '@material-ui/icons/GetApp';
import { Fragment } from 'react';

import jsonExport from 'jsonexport/dist';

import JSZip from 'jszip'
import jrQrcode from 'jr-qrcode'
import Swal from 'sweetalert2';

/*
const CustomDateTimeInput = ({ label, source, record = {} }) => {
    const {
        input: { onChange },
        meta: { touched, error }
    } = useField(source);
    let value = moment(record[source]).utc().format("yyyy-MM-DDTHH:mm")
    console.log(value)
    return (
        <TextField
            name={source}
            label={label}
            type="datetime-local"
            defaultValue={value}
            onChange={onChange}
            error={!!(touched && error)}
            helperText={touched && error}
        />
    );
};
*/

const CustomDateTimeInput = ({ resource, source, label, record = {} }) => {
    // console.log(resource, source, label)
    let translate = useTranslate()
    if (resource) {
        label = translate(`resources.${resource}.fields.${source}`)
    }
    return (
        <DateTimeInput label={label}
            defaultValue=""
            parse={v => moment(v).format("yyyy-MM-DDTHH:mm")}
            format={v => moment(v).format("yyyy-MM-DDTHH:mm")}
            key={source} source={source} />
    )
}
/*

class CustomDateTimeInput extends DateTimeInput {
    constructor(props) {
        props.parse = v => moment(v).add(16, 'hours').utc().format("yyyy-MM-DDTHH:mm")
        props.format = v => moment(v).utc().format("yyyy-MM-DDTHH:mm")
        super(props)
    }
}
*/

const CustomDateTimeField = ({ source, record = {}, resource, labeld = false, format = "yyyy-MM-DD" }) => {
    let value = ""
    if (record[source]) {
        value = moment(record[source]).format(format)
    }
    let translate = useTranslate()
    if (labeld) {
        return (
            <Labeled label={translate(`resources.${resource}.fields.${source}`)}>
                <span>{value}</span>
            </Labeled>
        );
    } else {
        return (
            <span>{value}</span>
        )
    }
}

CustomDateTimeField.propTypes = {
    label: PropTypes.string,
    record: PropTypes.object,
    source: PropTypes.string.isRequired,
};

const BulkExportQRButton = props => {
    const { data } = useListContext();
    const onClick = async () => {
        if (props.selectedIds.length < 1) {
            console.log('没有选中数据')
            return
        }
        Swal.fire({
            title: '正在生成二维码',
        })
        let zip = new JSZip()
        let canvas = document.createElement('canvas')
        canvas.width = 300
        canvas.height = 300
        let ctx = canvas.getContext('2d')

        let img = document.createElement('img')

        const fillTextWith = (text, char = '', length) => {
            let fill = length - text.length
            if (fill > 0) {
                for (let i = 0; i < fill; i++) {
                    text = char + text
                }
            }
            return text
        }

        const labelCode = (id) => {
            return new Promise(resolve => {
                let imgBase64 = jrQrcode.getQrBase64(data[id].code);
                img.src = imgBase64
                img.onload = () => {
                    ctx.font = "20px sans-serif"
                    ctx.textAlign = 'center';
                    ctx.drawImage(img, 22, 0, 256, 256)
                    ctx.fillText("CANTEL-" + fillTextWith('' + id, '0', 6), 150, 280);
                    let base64 = canvas.toDataURL("image/png").substr(22)
                    console.log(base64)
                    zip.file(`qrcode-${id}.jpg`, base64, { base64: true })
                    canvas.height = canvas.height
                    // document.body.appendChild(img)
                    // document.body.appendChild(canvas)
                    resolve()
                }
            })
        }

        for (let i = 0; i < props.selectedIds.length; i++) {
            const id = props.selectedIds[i];
            await labelCode(id)
        }
        let min = Math.min(...props.selectedIds)
        let max = Math.max(...props.selectedIds)
        zip.generateAsync({
            type: 'blob'
        }).then(function (content) {
            var filename = `二维码${min}-${max}.zip`;
            var eleLink = document.createElement('a');
            eleLink.download = filename;
            eleLink.style.display = 'none';
            eleLink.href = URL.createObjectURL(content);
            // document.body.appendChild(eleLink);
            eleLink.click();
            setTimeout(Swal.close, 1000)

            // document.body.removeChild(eleLink);
        });
        console.log(data, props.resource, props.selectedIds, zip)
    }
    return (
        <Button
            label="导出二维码"
            // disabled={loading}
            onClick={onClick}
        >
            <GetAppIcon />
        </Button>
    );
}

const QRBulkActionButtons = props => (
    <Fragment>
        <BulkExportQRButton  {...props} />
    </Fragment>
);

const scanLogExporter = async (records, fetchRelatedRecords) => {
    const relatedRecords = [
        {
            source: 'hospitalId',
            table: 'hospital',
            field: 'name'
        },
        {
            source: 'departmentId',
            table: 'department',
            field: 'name'
        },
        {
            source: 'consumableType',
            table: 'consumableType',
            field: 'type'
        }, {
            source: 'type',
            table: 'deviceType',
            field: 'type'
        }, {
            source: 'deviceId',
            table: 'devices',
            field: 'name'
        },
    ]
    if (relatedRecords) {
        records = records.map(record => {
            let ele = {
                ...record,
                ...record.device,
                ...record.qrcode
            }
            ele.code = ele.code.substr(0, 6) + '***'
            delete ele.device
            delete ele.qrcode
            return ele
        })
        for (let i = 0; i < relatedRecords.length; i++) {
            let related = relatedRecords[i]
            let res = await fetchRelatedRecords(records, related.source, related.table)
            console.log(res, records[0], related.source, related.table)
            records = records.map(record => {
                if (record[related.source]) {
                    return {
                        ...record,
                        [related.source]: res[record[related.source]][related.field]
                    }
                } else {
                    return record
                }
            })

            records.map(record => {
                if (record.createdAt) {
                    record.createdAt = record.createdAt.substr(0, 10)
                }
            })
        }
    }
    jsonExport(records, {
        headers: ['id', 'deviceId', 'hospitalId', 'departmentId', 'type', 'consumableType', 'codeId', 'code', 'createdAt']
    }, (err, csv) => {
        csv = csv.replace("deviceId", "SN")
        csv = csv.replace("type", "model")
        csv = csv.replace("createdAt", "date")
        csv = "\ufeff" + csv
        downloadCSV(csv, 'scanLog'); // download as 'posts.csv` file
    });
};


const QRGenButton = () => {
    const redirect = useRedirect()
    const onClick = () => {
        redirect('/foo')
    }
    return (
        <Button
            label="批量生成"
            onClick={onClick}
        >
            <IconEvent />
        </Button>
    )
}

const CustomDateFilter = () => (
    [
        <DateInput onClick={console.log} key="start" source="startDate" label="开始日期" alwaysOn />,
        <DateInput onClick={console.log} key="end" source="endDate" label="截止日期" alwaysOn />
    ]
)

export {
    CustomDateTimeInput,
    CustomDateTimeField,
    QRBulkActionButtons,
    scanLogExporter,
    QRGenButton,
    CustomDateFilter
}